import React, {useEffect, useState} from "react";
import { Form, Select } from "antd";

import {ProBox, type WrappedComponentProps} from "@yaf/pro-ui";
import { prompt } from "@/service";
import { RespDataType, getBindReportGroup, bindReportGroupToAccount, getAllReportGroupList } from '../../../api';

interface AuthReportProps extends WrappedComponentProps{
    accountId: string;
}

const AuthReport: React.FC<AuthReportProps> = (props) => {
    const { form, loading,  bindReportGroupIdList, allReportGroupList } = useAuthReport(props);

    return <ProBox loading={loading}>
        <Form
            form={form}
            labelCol={{span: 24}}
            wrapperCol={{span: 24}}
            initialValues={{bindReportGroupIdList}}
        >
            <Form.Item
                label="报告数据"
                name="bindReportGroupIdList"
            >
                <Select
                    mode="multiple"
                    allowClear={true}
                    filterOption={(inputValue, option) => {
                        // @ts-ignore
                        return option.children.includes(inputValue);
                    }}
                >
                    {allReportGroupList.map(({label, value}) => (<Select.Option key={value} value={value}>
                        {label}
                    </Select.Option>))}
                </Select>
            </Form.Item>
        </Form>
    </ProBox>
}

export default AuthReport;

const useAuthReport = (props: AuthReportProps) => {
    const { modalControl, accountId } = props;
    const [ form ] = Form.useForm();
    const [ loading, setLoading ] = useState(true);
    const [ allReportGroupList, setAllReportGroupList ] = useState<RespDataType.ReportGroupList>([]);
    const [ bindReportGroupIdList, setBindReportGroupIdList ] = useState<string[]>([]);

    useEffect(() => {
        modalControl.registerOk(handleSubmit)
    });

    useEffect(() => {
        setLoading(true);
        Promise.all([getAllReportGroupList(), getBindReportGroup(accountId)]).then(([allReportGroupResp, bindReportGroupResp] ) => {
            setAllReportGroupList(allReportGroupResp.data || []);
            setBindReportGroupIdList(bindReportGroupResp.data || []);
            setLoading(false);
        })
    }, [])

    const handleSubmit = () => {
        form.validateFields().then((values) => {
            const {bindReportGroupIdList} = values;
            bindReportGroupToAccount(accountId, bindReportGroupIdList).then(() =>{
                prompt.success("操作成功!");
                modalControl.close();
            }).catch(() => modalControl.hideSaving());

        }).catch(() => modalControl.hideSaving());
    }

    return { form, loading, bindReportGroupIdList, allReportGroupList }
}
